package com.bupt.liutong.admin.core.bo;

import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.transaction.annotation.Transactional;

import com.bupt.liutong.admin.core.base.BaseBo;
import com.bupt.liutong.admin.core.base.Constants;
import com.bupt.liutong.admin.core.dao.UserDao;
import com.bupt.liutong.admin.core.dto.User;
import com.bupt.liutong.admin.core.form.UserForm;
import com.bupt.liutong.util.BeanUtils;
import com.bupt.liutong.util.DateUtils;
import com.bupt.liutong.util.ListUtils;
import com.bupt.liutong.util.StringUtils;

public class UserBo extends BaseBo {

	private UserDao userDao;

	public List<UserForm> getUsersByPage(UserForm userForm, HttpServletRequest request) {
		User user = new User();
		sm.pagingWithCriteria(userForm, user, "core_user.getUsersCount", request);
		List<User> userList = userDao.getUsersByPage(user);
		List<UserForm> userFormList = BeanUtils.copyList(userList, UserForm.class);
		return userFormList;
	}
	
	/**
	 * 根据userName，取得1个用户
	 * 
	 * @param userForm
	 * @return
	 */
	public UserForm getUserByName(UserForm userForm) {
		UserForm resultForm = new UserForm();
		User user = userDao.getUserByName(userForm.getUserName());
		BeanUtils.copyProperties(resultForm, user);
		return resultForm;
	}
	
	public List<UserForm> getUserRolesByUserName(String userName){
		List<User> userList = userDao.getUserRolesByUserName(userName);
		if (!ListUtils.isEmpty(userList)) {
			List<UserForm> userFormList = BeanUtils.copyList(userList, UserForm.class);
			return userFormList;
		} else {
			return null;
		}
	}
	
	public void insertUser(UserForm userForm) {
		userForm.setPassword(Constants.DEFAULT_PASSWORD);
		register(userForm);
	}
	
	@Transactional
	public boolean register(UserForm userForm) {
		User user = new User();
		UserForm resultForm = this.getUserByName(userForm);
		if (resultForm != null && !StringUtils.isEmpty(resultForm.getUserName()))
			return false;
		else {
			BeanUtils.copyProperties(user, userForm);
			user.setRegTime(DateUtils.getCurTime());
			user.setLastLoginTime(user.getRegTime());
			userDao.insertUser(user);
			// 赋予普通会员权限
			user.setRoleId(3);
			userDao.insertUserRole(user);
			return true;
		}
	}
	
	public boolean changePassword(UserForm userForm) {
		User user = userDao.getUserByName(userForm.getUserName());
		if (user == null || StringUtils.isEmpty(user.getPassword())
				|| !user.getPassword().equals(userForm.getPassword())) {
			return false;
		} else {
			userForm.setPassword(userForm.getNewPassword());
			BeanUtils.copyProperties(user, userForm);
			userDao.changePassword(user);
			return true;
		}
	}
	
	public void handleCookie(HttpServletRequest request,
			HttpServletResponse response) {
		String state = request.getParameter("keepLoginState");
		if (state != null && state.equals("1")) {
			Cookie cookie = new Cookie("userName", request
					.getParameter("userName"));
			response.addCookie(cookie);
		}
	}
	
	@Transactional
	public void updateUser(UserForm userForm) {
		User user = new User();
		BeanUtils.copyProperties(user, userForm);
		userDao.updateUser(user);
	}
	
	@Transactional
	public void updatePassword(UserForm userForm) {
		User user = new User();
		BeanUtils.copyProperties(user, userForm);
		userDao.updateUser(user);
	}
	
	@Transactional
	public void resetPassword(String[] userNames) {
		if (userNames != null) {
			for (int i = 0; i < userNames.length; i++) {
				User user = new User();
				user.setUserName(userNames[i]);
				user.setPassword("123456");
				userDao.updateUser(user);
			}
		}
	}
	
	@Transactional
	public void updateUserRole(String userName, String[] roleIds) {
		userDao.deleteUserRoleByUserName(userName);
		if (roleIds != null && roleIds.length > 0) {
			for (String roleId : roleIds) {
				User user = new User();
				user.setUserName(userName);
				user.setRoleId(Integer.parseInt(roleId));
				userDao.insertUserRole(user);
			}
		}
	}
	
	@Transactional
	public void enableUsers(String[] userNames) {
		if (userNames != null) {
			for (String userName : userNames) {
				User user = new User();
				user.setUserName(userName);
				user.setEnabled(1);
				userDao.updateUserState(user);
			}
		}
	}
	
	@Transactional
	public void disableUsers(String[] userNames){
		if (userNames != null) {
			for (String userName : userNames) {
				User user = new User();
				user.setUserName(userName);
				user.setEnabled(0);
				userDao.updateUserState(user);
			}
		}
	}
	
	@Transactional
	public void deleteUsers(String[] userNames) {
		for (int i = 0; i < userNames.length; i++) {
			userDao.deleteUser(userNames[i]);
		}
	}

	public boolean validateKaptcha(HttpServletRequest request) {
		HttpSession session = request.getSession();
		String kaptchaExpected = (String) session
				.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		if (kaptchaExpected != null
				&& kaptchaExpected.equals(request.getParameter("kaptchafield"))) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 登陆验证
	 * 
	 * @param userForm
	 * @return
	 */
	public boolean validateLogin(UserForm userForm) {
		// 校验是否为空
		if (userForm == null || userForm.getUserName() == null
				|| userForm.getPassword() == null) {
			return false;
		}
		// 取1个用户
		User user = userDao.getUserByName(userForm.getUserName());
		// 校验是否为空
		if (user == null || user.getUserName() == null
				|| user.getPassword() == null) {
			return false;
		}
		
		// 校验用户名和密码
		if (userForm.getUserName().equals(user.getUserName())
				&& userForm.getPassword().equals(user.getPassword())) {
			return true;
		} else {
			return false;
		}
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

//  For test insert
//	@Transactional
//	public void insertUser(UserForm userForm) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, SQLException{
//		User user = new User();
//		long time1 = System.currentTimeMillis();
//		startBatch();
//		for(int i=0; i<500; i++){
//			BeanUtils.copyProperties(user, userForm);
//			user.setUserName(user.getUserName()+"App"+i);
//			userDao.insertUser(user);
//		}
//		long time2 = System.currentTimeMillis();
//		executeBatch();
//		System.out.println("time="+(time2-time1));
//	}
}
